package com.dinfo.test.init;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.apache.commons.beanutils.MethodUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisTemple implements InvocationHandler {


    public static SqlSessionFactory sqlfactory;

    public static void setFactory(SqlSessionFactory factory) {
          sqlfactory= factory;
    }

    public Object invoke(Object proxy, Method method,Object[] args)
                throws Throwable {
          SqlSession session =sqlfactory.openSession();
          Object obj =session.getMapper(method.getDeclaringClass());
          Object data = MethodUtils.invokeMethod(obj, method.getName(), args);
          session.close();
          return data;
    }

    public<T> T getMapper(Class<T> t) {
          return(T) Proxy.newProxyInstance(Thread.currentThread()
                      .getContextClassLoader(),new Class[]{ t },this);
    }

    public static SqlSessionFactory initSessionFactory(String path)
	{
		try {
			return new SqlSessionFactoryBuilder().build(new FileInputStream(new File(path)));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public static void init(String path)
	{
		MyBatisTemple.setFactory(initSessionFactory(path));
	}
    
}